<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-bind="$attrs"
    @open="handlerOpen"
    v-on="$listeners"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="form.roleDesc" type="textarea" maxlength="200" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button type="primary" @click="confirm('form')">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { postRole, detailRole, updateRole } from '@/api/rights'

const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
}

export default {
  name: 'ROLEDETAIL',
  props: {
    type: {
      type: Number,
      default: 1 // 1 添加
    },
    cb: {
      type: Function
    },
    id: {
      type: [Number, String]
    }
  },
  data() {
    return {
      form: {
        roleName: '',
        roleDesc: ''
      },
      rules
    }
  },
  computed: {
    title() {
      let str = ''
      if (this.type === 1) {
        str = '添加角色'
      } else if (this.type === 2) {
        str = '编辑角色'
      }
      return str
    }
  },
  methods: {
    handlerOpen() {
      this.resetForm('form')
      if (this.type === 2) {
        this.getRoleDetail()
      }
    },
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields()
    },
    confirm(formName) {
      if (this.type === 1) {
        this.submitForm(formName)
      } else if (this.type === 2) {
        this.editRole(formName)
      }
    },
    async getRoleDetail() {
      const res = await detailRole(this.id)
      this.form = { ...this.form, ...res }
    },
    editRole(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const data = {
            id: this.form.roleId,
            roleName: this.form.roleName,
            roleDesc: this.form.roleDesc
          }
          await updateRole(data)
          this.$message({
            message: '角色更新成功',
            type: 'success'
          })
          this.$emit('update:visible', false)
          this.cb && this.cb()
        } else {
          return false
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          await postRole(this.form)
          this.$message({
            message: '添加角色成功',
            type: 'success'
          })
          this.$emit('update:visible', false)
          this.cb && this.cb()
        } else {
          return false
        }
      })
    }
  }

}
</script>
